package art.java.concurrency.chapter04;

import java.util.concurrent.TimeUnit;

/**
 * @author <a href="eric_zheng@lanzuo.com.cn">eric</a>
 * @version 1.0.0
 * Description: 优雅的终止线程
 */
public class Shutdown {

    public static void main(String[] args) throws InterruptedException {
        Runner one = new Runner();
        Thread countThread = new Thread(one, "count1Thread");
        countThread.start();
        // 睡眠1秒。main线程对CountThread进行中断，使CountThread 能够感知而结束线程。
        TimeUnit.SECONDS.sleep(1);
        countThread.interrupt();
//        countThread.stop();
        Runner two = new Runner();
        countThread = new Thread(two, "count2Thread");
        countThread.start();
        // 睡眠1秒。main线程对Runner two进行中断，使CountThread 能够感知on为false而结束线程。
        TimeUnit.SECONDS.sleep(1);
        two.cancel();
    }

    static class Runner implements Runnable {
        private long i;
        private volatile boolean on = true;

        @Override
        public void run() {
            while (on && !Thread.currentThread().isInterrupted()) {
                i++;
            }

            System.out.println(Thread.currentThread().getName() + ", Count i = " + i);
        }

        public void cancel() {
            on = false;
        }

    }
}


